Solving the puzzle in javascript [on hold]

Posted by Gandalf StormCrow on Programmers See other posts from Programmers or by Gandalf StormCrow
Published on 2013-11-08T16:22:25Z Indexed on 2013/11/08 22:14 UTC
Read the original article Hit count: 227

Filed under:

I've recently try to brush up my javascript skills, so I have a friend who gives me puzzles from time to time to solve. Yesterday I got this :

function testFun() {
  f = {};
  for( var i=0 ; i<3 : i++ ) {
    f[i] = function() { alert("sum='+i+f.length); }
  }
return f;
}

Expected Results:
testFun()[0]() should alert “sum=0”
testFun()[1]() should alert “sum=2”
testFun()[2]() should alert “sum=4”

I did this which does like requested above:

function testFun() {
    var i,
        f = {};
    for (i = 0; i < 3; i++) {
        f[i] = (function(number) {
            return function() {
                alert("sum=" + (number * 2));
            }
        }(i));
    }
    return f;
}

Today I got new puzzle :

Name everything wrong with this javascript code, then tell how you would re-write it.

    function testFun(fInput) {
      f = fInput || {};
      // append three functions
      for( var i=0 ; i<3 : i++ ) {
        f[i] = function() { alert("sum='+i+f.length); }
      }
      return f;
    }

// Sample Expected Results (do not change)

    myvar = testFun();
    myvar[0](); // should alert “sum=0”
    myvar[1](); // should alert “sum=2”
    testFun(['a'])[2](); // should alert “sum=5”`enter code here

How do I accomplish the third case testFun(['a'])[2]()? Also could my answer from yesterday be written better and what can be improved if so?

© Programmers or respective owner

Related posts about JavaScript